package gui.admin.ticketsinfor;

import com.formdev.flatlaf.FlatIntelliJLaf;
import com.sun.org.apache.xpath.internal.operations.Or;
import database.TableDatabaseUsage;
import gui.admin.mtm.ATM1;
import gui.admin.mtm.FTM;
import info.UserOrder;

import javax.swing.*;
import javax.swing.plaf.FontUIResource;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.Enumeration;

public class Refund_Tickets extends JFrame {

        private JTextField ticketPriceField;
        private JTextArea refundReasonArea;
        private JRadioButton originalPaymentRefundRadio, cashRefundRadio;
        private JCheckBox specialCaseCheckBox;
        private JComboBox<String> refundTimeComboBox;
        private JLabel refundFeeLabel, totalRefundAmountLabel;
        private JTable jTable;
        private String OrderNo;
        private UserOrder cacheuserOrder = new UserOrder();

    public Refund_Tickets(){

            setTitle("退票管理");
            setSize(700, 500);
            setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            setLocationRelativeTo(null);
            orignalUI();
//            initUI();
            setResizable(false);
            setVisible(true);
    }

    private void orignalUI() {
        jTable= new JTable(FTM.getInstance());
        //头部欢迎文字
        JPanel jp = new JPanel();
        jp.setBounds(130, 30, 500, 60);
        JLabel jL = new JLabel("欢迎使用退票管理系统！");
        //创建文字对象

        jL.setFont(new Font("Serif", Font.BOLD, 33));
        jL.setForeground(Color.darkGray);
        jp.add(jL);
        this.add(jp);

        JButton btn1 = new JButton("处理退款");
        JButton btn2 = new JButton("查询");
        JButton btn3 = new JButton("待处理");
        JPanel panel = new JPanel();


        //按钮
        btn1.setBounds(510, 100, 125, 35);
        this.getContentPane().add(btn1);

        btn1.addActionListener(e -> {
            // TODO Auto-generated method stub
            System.out.println("退款订单按钮被点击了！");
            int selectedRow=jTable.getSelectedRow();
            if(selectedRow!=-1){
                String OrderNo = (String) jTable.getValueAt(selectedRow,0);
                String IDNo = (String) jTable.getValueAt(selectedRow,1);
                String Flight = (String) jTable.getValueAt(selectedRow,2);
                Date Fdate = (Date) jTable.getValueAt(selectedRow,3);
                String Fclass = (String) jTable.getValueAt(selectedRow,4);
                Float Discount = (Float) jTable.getValueAt(selectedRow,5);
                String OrderState = (String) jTable.getValueAt(selectedRow,6);
                Timestamp OrderTime = (Timestamp) jTable.getValueAt(selectedRow,7);
                System.out.println("你选择的订单为"+OrderNo);
                cacheuserOrder.setOrderNO(OrderNo);
                cacheuserOrder.setIDNO(IDNo);
                cacheuserOrder.setFlight(Flight);
                cacheuserOrder.setFdate(Fdate);
                cacheuserOrder.setFclass(Fclass);
                cacheuserOrder.setDiscount(Discount);
                cacheuserOrder.setOrderState(OrderState);
                cacheuserOrder.setOrderTime(OrderTime);
                // 根据用户选择执行相应操作
                new RefundTickets(cacheuserOrder);
            }else {
                JOptionPane.showMessageDialog(null, "请选择一行进行处理！");
            }

        });


        //查询按钮
        btn2.setBounds(270, 100, 90, 35);


        this.getContentPane().add(btn2);
        //订单号
        JLabel OrderLabel = new JLabel("订单号:");
        OrderLabel.setBounds(50, 100, 100, 35);

        JTextField fieldOrdNum = new JTextField("输入订单号");


        //监听事件：
        fieldOrdNum.addFocusListener(new FocusListener() {

            @Override
            public void focusLost(FocusEvent e) {
                //失去焦点时，用户尚未在文本框输入任何内容，依旧显示提示文字
                if (fieldOrdNum.getText().equals("")) {
                    fieldOrdNum.setForeground(Color.gray);
                    fieldOrdNum.setText("输入订单号");

                }

            }

            @Override
            public void focusGained(FocusEvent e) {
                //得到焦点时，文本框的提示文字和创建该对象时的提示文字一样，说明用户正要输入内容
                if (fieldOrdNum.getText().equals("输入订单号")) {
                    fieldOrdNum.setText("");
                    fieldOrdNum.setForeground(Color.black);
                }

            }
        });

        fieldOrdNum.setBounds(115, 100, 150, 35);

        this.getContentPane().add(OrderLabel);
        this.getContentPane().add(fieldOrdNum);
        btn2.addActionListener(e -> {
            System.out.println("查询按钮被点击了！");
            if(fieldOrdNum.getText()!=""&&fieldOrdNum.getText()!="输入订单号") {
                OrderNo = fieldOrdNum.getText();
                FTM.getInstance().userOrders = TableDatabaseUsage.getInstance().getUserRefOrderList(OrderNo);
                if(FTM.getInstance().userOrders.toArray().length==0){
                    JOptionPane.showMessageDialog(null, "订单未执行退款操作", "提示", JOptionPane.INFORMATION_MESSAGE);
                }
                fieldOrdNum.setText("输入订单号");
                jTable.updateUI();
            }
        });
        //按钮· `
        btn3.setBounds(380, 100, 110, 35);
        btn3.addActionListener(e -> {
            System.out.println("待处理按钮被点击了！");
            FTM.getInstance().userOrders = TableDatabaseUsage.getInstance().getRefundOrderList();
            jTable.updateUI();

        });
        this.getContentPane().add(btn3);


        this.getContentPane().add(panel);

        //表格


        JScrollPane scroll = new JScrollPane(jTable);

        scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        scroll.setPreferredSize(new Dimension(595, 200));
        jTable.setBackground(Color.white);
        jTable.setRowHeight(40);

        jTable.setGridColor(Color.pink);
        jTable.setSelectionBackground(Color.orange);
        //使表格文字居中
        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();

        centerRenderer.setHorizontalAlignment(JLabel.CENTER);


        for (int i = 0; i < jTable.getColumnCount(); i++) {
            jTable.getColumnModel().getColumn(i).setCellRenderer(centerRenderer);

        }


        panel.setBorder(BorderFactory.createEmptyBorder(150, 0, 0, 0));


        panel.add(scroll);
    }
    //处理退款事务
    class RefundTickets extends JFrame{
        JTextField OrderNoTextField;
        JTextField IDNoTextField;
        JTextField FlightTextField;
        JTextField FdateTextField;
        JTextField FclassTextField;
        JTextField DiscountTextField;
        JComboBox OrderStateComboBox;
        JTextField OrderTimeTextField;

        public RefundTickets(UserOrder userOrder) {
            super("处理退款需求");
            setSize(500,1000);
            Container container = getContentPane();
            container.setLayout(new BorderLayout());
            String[] OrderStateOptions = {"已付款", "已退款"};
            OrderNoTextField = new JTextField(cacheuserOrder.getOrderNO());
            IDNoTextField = new JTextField(cacheuserOrder.getIDNO());
            FlightTextField = new JTextField(cacheuserOrder.getFlight());
            FdateTextField = new JTextField(String.valueOf(cacheuserOrder.getFdate()));
            FclassTextField = new JTextField(cacheuserOrder.getFclass());
            DiscountTextField = new JTextField(String.valueOf(cacheuserOrder.getDiscount()));
            if(cacheuserOrder.getOrderState().equals(OrderStateOptions[0])) {
                OrderStateComboBox = new JComboBox<>(OrderStateOptions);
            }else{
                JOptionPane.showMessageDialog(null,"该订单已退款无法操作");
//                OrderStateComboBox.setEditable(false);
            }
            OrderTimeTextField = new JTextField(String.valueOf(cacheuserOrder.getOrderTime()));

            OrderNoTextField.setEditable(false);
            IDNoTextField.setEditable(false);
            FlightTextField.setEditable(false);
            FdateTextField.setEditable(false);
            FclassTextField.setEditable(false);
            DiscountTextField.setEditable(false);
            OrderTimeTextField.setEditable(false);
            JLabel l1 = new JLabel("订单号：");
            JLabel l2 = new JLabel("身份证号：");
            JLabel l3 = new JLabel("航班号：");
            JLabel l4 = new JLabel("航班日期：");
            JLabel l5 = new JLabel("舱位：");
            JLabel l6 = new JLabel("折扣：");
            JLabel l7 = new JLabel("订单状态：");
            JLabel l8= new JLabel("订票时间");


            // 设置居中
            l1.setHorizontalAlignment(JLabel.CENTER);
            l2.setHorizontalAlignment(JLabel.CENTER);
            l3.setHorizontalAlignment(JLabel.CENTER);
            l4.setHorizontalAlignment(JLabel.CENTER);
            l5.setHorizontalAlignment(JLabel.CENTER);
            l6.setHorizontalAlignment(JLabel.CENTER);
            l7.setHorizontalAlignment(JLabel.CENTER);
            l8.setHorizontalAlignment(JLabel.CENTER);

            JPanel inputPanel = new JPanel(new GridLayout(18, 2));
            inputPanel.add(l1);
            inputPanel.add(OrderNoTextField);
            inputPanel.add(l2);
            inputPanel.add(IDNoTextField);
            inputPanel.add(l3);
            inputPanel.add(FlightTextField);
            inputPanel.add(l4);
            inputPanel.add(FdateTextField);
            inputPanel.add(l5);
            inputPanel.add(FclassTextField);
            inputPanel.add(l6);
            inputPanel.add(DiscountTextField);
            inputPanel.add(l7);
            inputPanel.add(OrderStateComboBox);
            inputPanel.add(l8);
            inputPanel.add(OrderTimeTextField);

            JLabel j1 = new JLabel("票款金额:");
            j1.setHorizontalAlignment(JLabel.CENTER);
            inputPanel.add(j1);
            ticketPriceField = new JTextField();
            inputPanel.add(ticketPriceField);


            JLabel j2 = new JLabel("退票原因:");
            j2.setHorizontalAlignment(JLabel.CENTER);
            inputPanel.add(j2);
            refundReasonArea = new JTextArea(3, 15);
            inputPanel.add(refundReasonArea);

            JLabel j3 = new JLabel("退款方式:");
            j3.setHorizontalAlignment(JLabel.CENTER);
            inputPanel.add(j3);
            originalPaymentRefundRadio = new JRadioButton("原支付方式退款");
            cashRefundRadio = new JRadioButton("现金退款");
            ButtonGroup group = new ButtonGroup();
            group.add(originalPaymentRefundRadio);
            group.add(cashRefundRadio);
            JPanel refundMethodPanel = new JPanel(new FlowLayout());
            refundMethodPanel.add(originalPaymentRefundRadio);
            refundMethodPanel.add(cashRefundRadio);
            inputPanel.add(refundMethodPanel);

            JLabel j4 = new JLabel("是否为特殊情况:");
            j4.setHorizontalAlignment(JLabel.CENTER);
            inputPanel.add(j4);

            specialCaseCheckBox = new JCheckBox("是");
            inputPanel.add(specialCaseCheckBox);

            String[] refundTimeOptions = {"航班出发前24小时以上", "航班出发前2-24小时内", "航班出发前2小时内"};
            refundTimeComboBox = new JComboBox<>(refundTimeOptions);

            JLabel j5 = new JLabel("退票时间:");
            j5.setHorizontalAlignment(JLabel.CENTER);
            inputPanel.add(j5);
            inputPanel.add(refundTimeComboBox);

            container.add(inputPanel, BorderLayout.NORTH);

            JButton calculateButton = new JButton("计算退票费");
            calculateButton.addActionListener(e -> calculateRefundFee());
            container.add(calculateButton, BorderLayout.SOUTH);


            refundFeeLabel = new JLabel("退票手续费: ");
            refundFeeLabel.setHorizontalAlignment(JLabel.CENTER);
            totalRefundAmountLabel = new JLabel("总退款金额: ");
            totalRefundAmountLabel.setHorizontalAlignment(JLabel.CENTER);
            container.add(refundFeeLabel, BorderLayout.CENTER);
            container.add(totalRefundAmountLabel, BorderLayout.CENTER);
            setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            setVisible(true);
        }
    }

    private void calculateRefundFee() {
        double ticketPrice = Double.parseDouble(ticketPriceField.getText());
        double refundFeeRate;
        String selectedTime = (String) refundTimeComboBox.getSelectedItem();

        switch (selectedTime) {
            case "航班出发前24小时以上":
                refundFeeRate = 0.10; // 10% fee
                break;
            case "航班出发前2-24小时内":
                refundFeeRate = 0.20; // 20% fee
                break;
            case "航班出发前2小时内":
                refundFeeRate = 0.30; // 30% fee
                break;
            default:
                refundFeeRate = 0.10; // default to 10% fee if no valid selection
                break;
        }

        double refundFee = ticketPrice * refundFeeRate;
        double totalRefundAmount = ticketPrice - refundFee;

        if (specialCaseCheckBox.isSelected()) {
            refundFee = 0; // Full refund for special cases
            totalRefundAmount = ticketPrice;
        }

        refundFeeLabel.setText("退票手续费: " + String.format("%.2f", refundFee));
        totalRefundAmountLabel.setText("总退款金额: " + String.format("%.2f", totalRefundAmount));
    }



}
